package pdfsetter.core.schema.selectors;

import java.util.Iterator;

import pdfsetter.core.schema.advanced.FilePageSelection;
import pdfsetter.core.schema.advanced.FilePageSelector;
import pdfsetter.core.util.RandomAccessIterableIterator;

/**
 * RangePageSelector select pages from some range - it can be some fixed interval, or we can say that we want to choose pages from some page to the end of the
 * document. We do not choose pages which are improper - so we can say that we take pages from intersection of range interval and set of all pages from given
 * file.
 * 
 * @author Andrzej Dorobisz
 */
public class RangePageSelector implements FilePageSelector {
    private final int first;
    private final int last;

    public RangePageSelector(int first, int last) {
        this.first = first;
        this.last = last;
    }

    public RangePageSelector(int first) {
        this.first = first;
        this.last = -1;
    }

    @Override
    public FilePageSelection selectPages(int fileSize) {
        if (fileSize <= first)
            return new EmptyFilePageSelection();
        if (last < 0)
            return new RangePageSelection(first, fileSize - 1);
        else
            return new RangePageSelection(first, Math.min(last, fileSize - 1));
    }

    private class RangePageSelection implements FilePageSelection {
        private final int first;
        private final int size;

        public RangePageSelection(int first, int last) {
            this.first = first;
            size = last - first + 1;
        }

        @Override
        public Integer get(int index) {
            if (index >= size || index < 0)
                throw new IndexOutOfBoundsException();
            return index + first;
        }

        @Override
        public int size() {
            return size;
        }

        @Override
        public Iterator<Integer> iterator() {
            return new RandomAccessIterableIterator<Integer>(this);
        }
    }
}
